#!/bin/bash
# Python Service Deployment Script for BWG Server
# Function: Deploy matrix_python project to BWG remote server and start the service

# Set UTF-8 encoding support
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

# Set script name for logging
SCRIPT_NAME="deploy_python_bwg"

# ============================================
# Configuration and Global Variables
# ============================================

# Set working directory
export AWS="${AWS:-$HOME/workspace}"

# Log level: 0=ERROR, 1=WARN, 2=INFO, 3=DEBUG
LOG_LEVEL="${LOG_LEVEL:-2}"

# Script directory
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Source and target paths
SOURCE_DIR="$AWS/demo/matrix_python"
TEMP_DIR="/tmp/python_deployment"
TARGET_DIR="/root/matrix_python"

# Remote server configuration (based on SSH config)
REMOTE_USER="root"
REMOTE_HOST="bwg"
REMOTE_PORT="29692"

# Service configuration
SERVICE_PORT="55055"
SERVICE_NAME="matrix_python"

# Log function
log() {
    local level=$1
    local message=$2
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    local level_str
    
    case $level in
        0) level_str="ERROR" ;;
        1) level_str="WARN"  ;;
        2) level_str="INFO"  ;;
        3) level_str="DEBUG" ;;
        *) level_str="UNKNOWN" ;;
    esac
    
    if [ $level -le $LOG_LEVEL ]; then
        echo "[$timestamp] [$SCRIPT_NAME] [$level_str] $message"
    fi
}

# Show separator
show_separator() {
    local char=${1:-"="}
    local length=${2:-50}
    printf "%*s\n" "$length" | tr ' ' "$char"
}

# Check if command exists
check_command() {
    local cmd=$1
    local desc=$2
    
    if ! command -v "$cmd" > /dev/null 2>&1; then
        log 0 "Error: Command $cmd ($desc) not found, please install it first."
        return 1
    fi
    return 0
}

# Cleanup function
cleanup() {
    log 2 "Cleaning up temporary files..."
    rm -rf "$TEMP_DIR"
}

# Trap to ensure cleanup happens
trap cleanup EXIT

# ============================================
# Deployment Functions
# ============================================

# Check prerequisites
check_prerequisites() {
    log 2 "Checking prerequisites..."
    
    # Check required commands
    check_command "ssh" "SSH client" || return 1
    check_command "scp" "SCP client" || return 1
    check_command "tar" "Tar archiver" || return 1
    
    # Check source directory
    if [ ! -d "$SOURCE_DIR" ]; then
        log 0 "Error: Source directory does not exist: $SOURCE_DIR"
        return 1
    fi
    
    # Check key files
    if [ ! -f "$SOURCE_DIR/app.py" ]; then
        log 0 "Error: app.py not found in source directory"
        return 1
    fi
    
    if [ ! -f "$SOURCE_DIR/requirements.txt" ]; then
        log 0 "Error: requirements.txt not found in source directory"
        return 1
    fi
    
    log 2 "All prerequisites check passed"
    return 0
}

# Prepare deployment package
prepare_deployment() {
    log 2 "Preparing deployment package..."
    
    # Create temporary directory
    rm -rf "$TEMP_DIR"
    mkdir -p "$TEMP_DIR"
    
    # Copy files to temporary directory
    log 2 "Copying files to temporary directory..."
    cp -r "$SOURCE_DIR" "$TEMP_DIR/"
    
    # Create deployment package
    log 2 "Creating deployment package..."
    cd "$TEMP_DIR" || return 1
    if ! tar -czf "matrix_python.tar.gz" "matrix_python"; then
        log 0 "Error: Failed to create deployment package"
        return 1
    fi
    
    log 2 "Deployment package created successfully"
    return 0
}

# Transfer files to remote server
transfer_files() {
    log 2 "Transferring files to remote server..."
    
    # Transfer deployment package
    if ! scp -P "$REMOTE_PORT" "$TEMP_DIR/matrix_python.tar.gz" "$REMOTE_USER@$REMOTE_HOST:/tmp/"; then
        log 0 "Error: Failed to transfer deployment package"
        return 1
    fi
    
    # Transfer service script
    local service_script_content="#!/bin/bash
# Matrix Python Service Script

export PATH=/usr/local/bin:/usr/bin:/bin

# Function to check if service is running
is_service_running() {
    pgrep -f \"python3.*app.py\" > /dev/null
}

# Function to start service
start_service() {
    if is_service_running; then
        echo \"Service is already running\"
        return 1
    fi
    
    cd $TARGET_DIR
    # Use python3 since we've installed it
    nohup python3 app.py > service.log 2>&1 &
    echo \"Service started with python3, PID \$!\"
    return 0
}

# Function to stop service
stop_service() {
    if ! is_service_running; then
        echo \"Service is not running\"
        return 1
    fi
    
    pkill -f \"python3.*app.py\"
    echo \"Service stopped\"
    return 0
}

# Function to restart service
restart_service() {
    stop_service
    sleep 2
    start_service
}

# Function to check service status
check_status() {
    if is_service_running; then
        echo \"Service is running\"
        # Show the process
        pgrep -af \"python3.*app.py\"
    else
        echo \"Service is not running\"
    fi
}

# Main function
case \"\$1\" in
    start)
        start_service
        ;;
    stop)
        stop_service
        ;;
    restart)
        restart_service
        ;;
    status)
        check_status
        ;;
    *)
        echo \"Usage: \$0 {start|stop|restart|status}\"
        exit 1
        ;;
esac
"
    
    echo "$service_script_content" > "$TEMP_DIR/service.sh"
    chmod +x "$TEMP_DIR/service.sh"
    
    if ! scp -P "$REMOTE_PORT" "$TEMP_DIR/service.sh" "$REMOTE_USER@$REMOTE_HOST:/tmp/"; then
        log 0 "Error: Failed to transfer service script"
        return 1
    fi
    
    log 2 "Files transferred successfully"
    return 0
}

# Setup remote environment
setup_remote_environment() {
    log 2 "Setting up remote environment..."
    
    # Extract deployment package and install dependencies
    log 2 "Extracting deployment package and installing dependencies..."
    if ! ssh -p "$REMOTE_PORT" "$REMOTE_USER@$REMOTE_HOST" "
        # Fix yum repos if needed
        if ! yum list available | grep -q python3; then
            sed -i \\\"s/mirrorlist/#mirrorlist/g\\\" /etc/yum.repos.d/CentOS-Base.repo
            sed -i \\\"s|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g\\\" /etc/yum.repos.d/CentOS-Base.repo
            yum clean all && yum makecache
        fi
        
        # Install Python 3 and dependencies if not present
        if ! command -v python3 > /dev/null 2>&1; then
            yum install -y python3 python3-pip gcc python3-devel
        fi
        
        # Install required Python packages
        pip3 install flask psutil==5.9.0 flask-cors
        
        # Extract deployment package
        cd /tmp &&
        tar -xzf matrix_python.tar.gz &&
        rm -rf $TARGET_DIR &&
        mkdir -p $TARGET_DIR &&
        mv matrix_python/* $TARGET_DIR/ &&
        chown -R root:root $TARGET_DIR
    "; then
        log 0 "Error: Failed to setup remote environment"
        return 1
    fi
    
    # Transfer service script to target directory
    log 2 "Transferring service script to target directory..."
    if ! ssh -p "$REMOTE_PORT" "$REMOTE_USER@$REMOTE_HOST" "
        mv /tmp/service.sh $TARGET_DIR/
    "; then
        log 0 "Error: Failed to move service script to target directory"
        return 1
    fi
    
    # Make sure service script is executable
    if ! ssh -p "$REMOTE_PORT" "$REMOTE_USER@$REMOTE_HOST" "
        chmod +x $TARGET_DIR/service.sh
    "; then
        log 0 "Error: Failed to set service script permissions"
        return 1
    fi
    
    log 2 "Remote environment setup completed"
    return 0
}

# Start service
start_service() {
    log 2 "Starting service..."
    
    # Start the service
    if ! ssh -p "$REMOTE_PORT" "$REMOTE_USER@$REMOTE_HOST" "$TARGET_DIR/service.sh start"; then
        log 0 "Error: Failed to start service"
        return 1
    fi
    
    # Wait a moment for service to start
    sleep 3
    
    # Check service status
    log 2 "Checking service status..."
    if ssh -p "$REMOTE_PORT" "$REMOTE_USER@$REMOTE_HOST" "$TARGET_DIR/service.sh status"; then
        log 2 "Service started successfully"
    else
        log 1 "Warning: Service may not have started correctly"
    fi
    
    return 0
}

# Test service
test_service() {
    log 2 "Testing service..."
    
    # Test API endpoints
    local server_ip="96.45.185.60"
    
    # Test site-config endpoint
    log 2 "Testing /api/site-config endpoint..."
    if command -v curl > /dev/null 2>&1; then
        local response
        response=$(curl -s -m 10 "http://$server_ip:$SERVICE_PORT/api/site-config" 2>/dev/null)
        if [ -n "$response" ]; then
            log 2 "Site-config API test passed"
        else
            log 1 "Warning: Site-config API test failed or timed out"
        fi
    else
        log 1 "Warning: curl not found, skipping API tests"
    fi
    
    return 0
}

# Main deployment function
deploy_python_service() {
    show_separator
    log 2 "Starting Python service deployment to BWG server"
    show_separator
    
    # Check prerequisites
    if ! check_prerequisites; then
        log 0 "Prerequisites check failed"
        return 1
    fi
    
    # Prepare deployment package
    if ! prepare_deployment; then
        log 0 "Failed to prepare deployment package"
        return 1
    fi
    
    # Transfer files
    if ! transfer_files; then
        log 0 "Failed to transfer files"
        return 1
    fi
    
    # Setup remote environment
    if ! setup_remote_environment; then
        log 0 "Failed to setup remote environment"
        return 1
    fi
    
    # Start service
    if ! start_service; then
        log 0 "Failed to start service"
        return 1
    fi
    
    # Test service
    test_service
    
    show_separator
    log 2 "Python service deployment completed successfully!"
    log 2 "Service is now running on http://96.45.185.60:$SERVICE_PORT"
    log 2 "You can manage the service using: ssh -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST '$TARGET_DIR/service.sh {start|stop|restart|status}'"
    show_separator
    
    return 0
}

# Show help information
show_help() {
    echo "Python Service Deployment Tool for BWG Server"
    echo ""
    echo "Usage: $0 [options]"
    echo ""
    echo "Function: Deploy matrix_python project to BWG remote server and start the service"
    echo ""
    echo "Options:"
    echo "  --help, -h        Show this help message"
    echo ""
    echo "Environment variables:"
    echo "  AWS        Working directory (default: \$HOME/workspace)"
    echo "  LOG_LEVEL  Log level (0=ERROR, 1=WARN, 2=INFO, 3=DEBUG)"
    echo ""
}

# Main function
main() {
    # Get command parameters
    local subcommand="$1"
    
    # Process different commands
    case "$subcommand" in
        "help"|"--help"|"-h")
            show_help
            ;;
        "")
            # No parameters, execute deployment
            deploy_python_service
            ;;
        *)
            # Unknown command
            log 0 "Error: Unknown command $subcommand"
            show_help
            return 1
            ;;
    esac
    
    return $?
}

# Execute main function
main "$@"